<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\admin\middleware\Auth;
use app\BaseController;
use think\facade\View;
use app\common\model\User\Pay as PayModel;
use app\common\model\User\User as UserModel;
use app\common\model\User\Record as RecordModel;
use app\common\validate\User\Record as RecordValidate;
use think\exception\ValidateException;
use think\facade\Db;

class Pay extends BaseController
{
    protected $middleware = [
        Auth::class
    ];

    public function index()
    {
        $nav_title = [
            'nav_title' => '用户管理',
            'title' => '用户充值记录'
        ];

        // 接收查询字段
        $SearchField = $this->request->param('search_field', 'nickname');

        $keyword = $this->request->param('keyword', '');

        $userid = $this->request->param('userid', 0);

        $where = [];

        if (!empty($SearchField) && !empty($keyword)) {
            if ($SearchField == 'nickname') {
                $where[] = ['user.nickname', 'LIKE', "%$keyword%"];
            } elseif ($SearchField == 'adminnickname') {

                $where[] = ['admin.nickname', 'LIKE', "%$keyword%"];
            }
        } else {
            $keyword = '请输入相应的内容';
        }

        if (!empty($userid)) {
            $where[] = ['userid', '=', $userid];
        }

        $PayList = PayModel::hasWhere('user', [['deletetime', 'EXP', Db::raw('IS NULL')]])->hasWhere('admin', [], '*', 'LEFT')->where($where)->order('createtime', 'desc')->paginate(['list_rows' => 5, 'query' => request()->param()]);

        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $num = ($PayList->currentPage() - 1) * $PayList->listRows();

        return View::fetch('', [
            'nav_title' => $nav_title,
            'PayList' => $PayList,
            'num' => $num,
            'SearchField' => $SearchField,
            'keyword' => $keyword
        ]);
    }


    // 删除
    public function del()
    {
        if ($this->request->isAjax()) {
            $payid = $this->request->param('payid', 0);

            if (empty($payid)) {
                $this->error('请选择需要删除的记录');
            }

            if (is_array($payid)) {
                $PayList = PayModel::whereIn('id', $payid)->column('id');
                $PayStatus = PayModel::whereIn('id', $payid)->column('status');

                $NotId = '';

                foreach ($payid as $item) {
                    if (!in_array($item, $PayList)) {
                        $NotId .= $item . ',';
                    }
                }

                foreach ($PayStatus as $value) {
                    if ($value == 0) {
                        $this->error('选中的记录存在未审核的,请重新选中');
                    }
                }

                $NotId = rtrim($NotId, ',');

                if (!empty($NotId)) {
                    $this->error("ID：{$NotId}不存在，请重新选择");
                }

                $result = PayModel::destroy($payid);

                if ($result !== true) {
                    $this->error('批量删除失败');
                } else {
                    $this->success('批量删除成功');
                }
            } else {
                // 单条删除
                $Pay = PayModel::find($payid);

                if (!$Pay) {
                    $this->error('该充值记录不存在，无法删除');
                }

                // 真实删除
                $result = PayModel::destroy($payid);

                if ($result !== true) {
                    $this->error('删除失败');
                } else {
                    $this->success('删除成功');
                }
            }
        }
    }

    // 审核
    public function status()
    {
        $payid = $this->request->param('payid');

        $action = $this->request->param('action');

        if (empty($payid)) {
            $this->error('请选择需要操作的记录');
        }

        // 用户更新积分
        // 消费记录 插入审核记录
        // 充值表 更新状态和审核的管理员

        // 开启事务
        UserModel::startTrans();
        PayModel::startTrans();
        RecordModel::startTrans();

        if (is_array($payid)) {

            $PayList = PayModel::whereIn('id', $payid)->select();
            if ($action == 'adopt') 
            {

                foreach($PayList as $item)
                {
                    if($item['status'] != 0)
                    {
                        $this->error('所选择的存在已审核的记录');
                    }
                }


                // 存放userid
                $Userid = [];

                // 插入消费记录
                $RecordData = [];

                // 更新充值表
                $PayData = [];

                foreach ($PayList as $item) {
                    $Userid[$item['userid']][] = $item['id'];

                    $RecordData[] = [
                        'point' => $item['point'],
                        'content' => "您的充值【{$item['content']}】审核成功了，积分已到账",
                        'state' => 3,
                        'userid' => $item['userid']
                    ];

                    $PayData[] = [
                        'id' => $item['id'],
                        'status' => 1,
                        'adminid' => $this->request->LoginAdmin['id']
                    ];
                }

                // 更新用户积分
                $UserData = [];

                foreach ($Userid as $key => $item) {
                    $UpdatePoint = PayModel::whereIn('id', $item)->sum('point');

                    $UserPoint = UserModel::where('id', $key)->value('point');

                    $UpdatePoint = $UpdatePoint ? $UpdatePoint : 0;

                    $UserData[] = [
                        'id' => $key,
                        'point' => bcadd((string)$UserPoint, (string)$UpdatePoint),
                    ];
                }

                // 更新用户表
                $User = new UserModel();

                $UserStatus = $User->saveAll($UserData);

                if ($UserStatus != true) {
                    $this->error('更新积分失败');
                }


                $Record = new RecordModel();

                $RecordStatus = $Record->saveAll($RecordData);

                // halt($RecordStatus);

                if ($RecordStatus != true) {
                    UserModel::rollback();
                    $this->error('消费记录新增失败');
                }

                $pay = new PayModel();

                $PayStatus = $pay->saveAll($PayData);

                if ($PayStatus != true) {
                    UserModel::rollback();
                    RecordModel::rollback();
                    $this->error('更新充值记录失败');
                }

                if ($UserStatus != true || $RecordStatus != true || $PayStatus != true) {
                    UserModel::rollback();
                    RecordModel::rollback();
                    PayModel::rollback();
                    $this->error('操作失败');
                } else {
                    UserModel::commit();
                    RecordModel::commit();
                    PayModel::commit();
                    $this->success('操作成功');
                }
            }elseif($action == 'fail')
            {

                foreach($PayList as $item)
                {
                    if($item['status'] != 0)
                    {
                        $this->error('所选择的存在已审核的记录');
                    }
                }

                // 插入消费记录
                $RecordData = [];

                // 更新充值表
                $PayData = [];

                foreach ($PayList as $item) {

                    $RecordData[] = [
                        'point' => 0,
                        'content' => "您的充值【{$item['content']}】审核失败了,已退款到您的账户了，请重新充值",
                        'state' => 3,
                        'userid' => $item['userid']
                    ];

                    $PayData[] = [
                        'id' => $item['id'],
                        'status' => 2,
                        'adminid' => $this->request->LoginAdmin['id']
                    ];
                }

                $Record = new RecordModel();

                $RecordStatus = $Record->saveAll($RecordData);

                if ($RecordStatus != true) {
                    UserModel::rollback();
                    $this->error('消费记录新增失败');
                }

                $pay = new PayModel();

                $PayStatus = $pay->saveAll($PayData);

                if ($PayStatus != true) {
                    UserModel::rollback();
                    RecordModel::rollback();
                    $this->error('更新充值记录失败');
                }

                if ($RecordStatus != true || $PayStatus != true) {
                    UserModel::rollback();
                    RecordModel::rollback();
                    PayModel::rollback();
                    $this->error('操作失败');
                } else {
                    UserModel::commit();
                    RecordModel::commit();
                    PayModel::commit();
                    $this->success('操作成功');
                }
                
            }
        } else {
            $pay = PayModel::find($payid);

            if (!$pay) {
                $this->error('该记录不存在');
            }

            if ($action == 'adopt') {
                // 用户数据
                $User = UserModel::find($pay['userid']);

                $UpdatePoint = bcadd((string)$User['point'], (string)$pay['point']);

                // 更新数据
                $UserData = [
                    'point' => $UpdatePoint
                ];

                $UserStatus = $User->save($UserData);

                if ($UserStatus !== true) {
                    $this->error('更新积分失败');
                }

                $RecordData = [
                    'point' => $pay['point'],
                    'content' => "您的充值【{$pay['content']}】审核成功了，积分已到账",
                    'state' => 3,
                    'userid' => $pay['userid']
                ];

                try {
                    validate(RecordValidate::class)->check($RecordData);
                } catch (ValidateException $e) {
                    UserModel::rollback();
                    $this->error($e->getError());
                }

                $RecordModel = new RecordModel();

                $RecordStatus = $RecordModel->save($RecordData);

                if ($RecordStatus !== true) {
                    UserModel::rollback();
                    $this->error('消费记录新增失败');
                }

                $PayData = [
                    'status' => 1,
                    'adminid' => $this->request->LoginAdmin['id']
                ];

                $PayStatus = $pay->save($PayData);

                if ($PayStatus !== true) {
                    UserModel::rollback();
                    RecordModel::rollback();
                    $this->error('更新充值记录失败');
                }

                if ($UserStatus !== true || $RecordStatus !== true || $PayStatus !== true) {
                    UserModel::rollback();
                    RecordModel::rollback();
                    PayModel::rollback();
                    $this->error('操作失败');
                } else {
                    UserModel::commit();
                    RecordModel::commit();
                    PayModel::commit();
                    $this->success('操作成功');
                }
            } elseif ($action == 'fail') {
                $RecordData = [
                    'point' => 0,
                    'content' => "您的充值【{$pay['content']}】审核不通过了，已退款到您的账户了，请重新充值",
                    'state' => 3,
                    'userid' => $pay['userid']
                ];

                try {
                    validate(RecordValidate::class)->check($RecordData);
                } catch (ValidateException $e) {
                    UserModel::rollback();
                    $this->error($e->getError());
                }

                $RecordModel = new RecordModel();

                $RecordStatus = $RecordModel->save($RecordData);

                if ($RecordStatus !== true) {
                    UserModel::rollback();
                    $this->error('消费记录新增失败');
                }

                $PayData = [
                    'status' => 2,
                    'adminid' => $this->request->LoginAdmin['id']
                ];

                $PayStatus = $pay->save($PayData);

                if ($PayStatus !== true) {
                    UserModel::rollback();
                    RecordModel::rollback();
                    $this->error('消费记录新增失败');
                }

                if ($RecordStatus !== true || $PayStatus !== true) {
                    UserModel::rollback();
                    RecordModel::rollback();
                    PayModel::rollback();
                    $this->error('操作失败');
                } else {
                    UserModel::commit();
                    RecordModel::commit();
                    PayModel::commit();
                    $this->success('操作成功');
                }
            }
        }
    }
}
